package com.sdhs.framework.web.service;

import javax.annotation.Resource;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sdhs.common.core.domain.entity.vo.SysUserVo;
import com.sdhs.common.core.domain.model.LoginBody;
import com.sdhs.common.utils.*;
import com.sdhs.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.sdhs.common.constant.CacheConstants;
import com.sdhs.common.constant.Constants;
import com.sdhs.common.constant.UserConstants;
import com.sdhs.common.core.domain.entity.SysUser;
import com.sdhs.common.core.domain.model.LoginUser;
import com.sdhs.common.core.redis.RedisCache;
import com.sdhs.common.exception.ServiceException;
import com.sdhs.common.exception.user.BlackListException;
import com.sdhs.common.exception.user.CaptchaException;
import com.sdhs.common.exception.user.CaptchaExpireException;
import com.sdhs.common.exception.user.UserNotExistsException;
import com.sdhs.common.exception.user.UserPasswordNotMatchException;
import com.sdhs.common.utils.ip.IpUtils;
import com.sdhs.framework.manager.AsyncManager;
import com.sdhs.framework.manager.factory.AsyncFactory;
import com.sdhs.framework.security.context.AuthenticationContextHolder;
import com.sdhs.system.service.ISysConfigService;
import com.sdhs.system.service.ISysUserService;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 登录校验方法
 * 
 * @author engineering
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 通过统一集成平台跳转过来的链接，根据用户id自动登录
     * @param vo
     * @return
     */
    public String loginForApiRedirect(SysUserVo vo)
    {

        //获取用户信息
        SysUser user = userService.selectUserById(vo.getUserId());
        vo.setUserName(user.getUserName());
        valiRedirectData(vo);
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), null);
            AuthenticationContextHolder.setContext(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));

        //获取角色数据
        user = loginService.getUserPost(user);

        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);

        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        loginUser.setUserId(vo.getUserId());
        loginUser.setPermissions(permissions);

        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public void valiRedirectData(SysUserVo vo)
    {
        try {
            String d_data = AESUtils.decrypt(vo.getValiData());
            String[] param = d_data.split("##");
            if(!vo.getTaskId().equals(param[0]) || !vo.getAppCode().equals(param[1]))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(vo.getUserName(), Constants.LOGIN_FAIL, MessageUtils.message("非法链接,请确认链接来源是否合法。")));
                throw new UserNotExistsException();
            }
        } catch (Exception e) {
            throw new UserNotExistsException();
        }
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(String userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    public SysUser getUserPost(SysUser user){
        return  userService.getUserPost(user);
    }


    /**
     * 根据竹云返回的code获取相应用户信息
     * @param code
     * @param login
     * @return
     */
    public LoginBody getUser(String code, LoginBody login){
        //获取token数据
        Map<String,Object> tokenParm = new HashMap<String,Object>();
        tokenParm.put("client_id","yfzhyw");
        tokenParm.put("client_secret","2e41fde525a34ef8a8d23bb90ebfdb06");
        tokenParm.put("code",code);
        tokenParm.put("grant_type","authorization_code");
        String tokenStr = HttpUtil.post("https://user.sdhsg.com/idp/oauth2/getToken",tokenParm);
        JSONObject json = JSONUtil.parseObj(tokenStr);
        //获取token
        String token = json.getStr("access_token");
        //当获取到token数据的时候
        if(TextUtil.isNotNull(token)){
            //根据token 获取用户信息
            Map<String,Object> userParm = new HashMap<String,Object>();
            userParm.put("access_token",token);
            userParm.put("client_id","yfzhyw");
            String userStr = HttpUtil.get("https://user.sdhsg.com/idp/oauth2/getUserInfo",userParm);
            JSONObject userJson = JSONUtil.parseObj(userStr);
            JSONArray userArray = JSONUtil.parseArray(userJson.get("spRoleList"));
            if(!(userArray.isEmpty())){
                login.setUsername(userArray.get(0)+"");
                login.setPassword(token);
            }
        }
        return login;
    }
}
